package com.example.securitydemo.service.impl;

import com.example.securitydemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class SecurityUserService implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.example.securitydemo.model.po.User user = userService.selectByUserName(username);
        if(user == null) throw new UsernameNotFoundException("User not exist!");
        List<String> roleList = userService.selectUserRoleByUsername(username);
        List<String> authorityList = userService.selectUserAuthorityByUsername(username);
        // ROLE 需要包装一下
        List<String> rList = roleList.stream().map(s -> "ROLE_" + s).collect(Collectors.toList());
        List<String> securityAuthorityList = new ArrayList<>(rList.size()+authorityList.size());
        securityAuthorityList.addAll(rList);
        securityAuthorityList.addAll(authorityList);
        return new User(username,passwordEncoder.encode(user.getPassword()),
//                Arrays.asList(new SimpleGrantedAuthority("admin"))
                // 普通字段视为权限Authority, ROLE_ 打头的视为角色
                AuthorityUtils.createAuthorityList(StringUtils.collectionToCommaDelimitedString(securityAuthorityList))
                );
    }


}
